package com.example.zhunongzonghe.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.zhunongzonghe.beans.ZnFarmhouseBean;
import com.example.zhunongzonghe.common.JsonUtils;
import com.example.zhunongzonghe.common.Result;
import com.example.zhunongzonghe.entity.ZnFarmhouse;
import com.example.zhunongzonghe.entity.ZnHouseEvaluate;
import com.example.zhunongzonghe.service.IZnFarmhouseService;
import com.example.zhunongzonghe.service.ZnHouseEvaluateService;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.security.Principal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/znFarmhouse")
public class ZnFarmhouseController  {
    @Autowired
    private IZnFarmhouseService znFarmhouseService;
    @Resource
    private ZnHouseEvaluateService evaluateService;

    //后台：分页查询全部农家乐，分页搜索
    @GetMapping("/SearchHouseAll")
    public Result<Page> SearchHouseAll(@RequestParam("pageId") Integer pageId,
                                       @RequestParam("pageSize") Integer pageNum,
                                       @RequestParam("input") Object SearchInfo){
        Page<ZnFarmhouse> znFarmhousePage = znFarmhouseService.SearcHouseAll(pageId,pageNum,SearchInfo);
        return new Result<>(true,"查询成功",200,znFarmhousePage);
    }
    //后台：编辑
    @PutMapping("/editorParamHouse")
    public Result<ZnFarmhouse> editorParamHouse(@RequestBody ZnFarmhouse znFarmhouse) throws JsonProcessingException {
        System.out.println("传过来的数据为"+znFarmhouse);
        znFarmhouse.setUpdateTime(LocalDateTime.now());
        String address = znFarmhouse.getHouseRregion().replace(",","")
                +znFarmhouse.getDistrictAddress();
        String location = getGeocoding(address);
        znFarmhouse.setHouseLatitude(location);
        znFarmhouseService.updateById(znFarmhouse);
        return new Result<>(true,"编辑成功",200);
    }
    //后台：新增
    @PostMapping("/addFarmHouse")
    public Result<ZnFarmhouse> addFarmHouse(@RequestBody ZnFarmhouse znFarmhouse) throws JsonProcessingException {
        String address = znFarmhouse.getHouseRregion().replace(",","")
                +znFarmhouse.getDistrictAddress();
        String location = getGeocoding(address);
        znFarmhouse.setHouseLatitude(location);
        znFarmhouse.setCreateTime(LocalDateTime.now());
        znFarmhouseService.save(znFarmhouse);
        return new Result<>(true,"添加成功",200);
    }
    //后台：删除
    @DeleteMapping("/delParamHouse/{houseId}")
    public Result<ZnFarmhouse> delParamHouse(@PathVariable Integer houseId){
        znFarmhouseService.removeById(houseId);
        LambdaQueryWrapper<ZnHouseEvaluate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ZnHouseEvaluate::getHouseId,houseId);
        List<ZnHouseEvaluate> znHouseEvaluates = evaluateService.list(queryWrapper);
        evaluateService.removeByIds(znHouseEvaluates);
        return new Result<>(true,"删除成功",200);
    }

    /**
     * 首页查询全部农家乐
     * @return
     */
    @GetMapping("/SearchHomeAll")
    public Result<List<ZnFarmhouse>> SearchHomeAll(){
        List<ZnFarmhouse> znFarmhouses = znFarmhouseService.SearcHomeHouseAll();
        return new Result<>(true,"查询成功",200,znFarmhouses);
    }

    /**
     * 已登录单个农家乐信息
     * @param houseId
     * @return znFarmhouseBean
     */
    @GetMapping("/HouseDetails/{houseId}")
    public Result HouseDetails(@PathVariable Integer houseId, Principal principal){
        ZnFarmhouseBean znFarmhouseBean = znFarmhouseService.HouseDetails(houseId,principal.getName());
        return new Result<>(true,"查询成功",200,znFarmhouseBean);
    }
    /**
     * 未登录单个农家乐信息
     * @param houseId
     * @return znFarmhouseBean
     */
    @GetMapping("/NotLogHouseDetails/{houseId}")
    public Result NotLogHouseDetails(@PathVariable Integer houseId){
        ZnFarmhouseBean znFarmhouseBean = znFarmhouseService.NotLogHouseDetails(houseId);
        return new Result<>(true,"查询成功",200,znFarmhouseBean);
    }

    @GetMapping("/SearchHousePage")
    public Result<Page> SearchHousePage(@RequestParam("pageId") Integer pageId,
                                        @RequestParam("pageSize") Integer pageNum){
        Page<ZnFarmhouse> znFarmhousePage = znFarmhouseService.ZnFarmhousePage(pageId,pageNum);
        return new Result<>(true,"查询成功",200,znFarmhousePage);
    }

    /**
     * 通过位置获取高德地理编码
     * @param address
     * @return
     * @throws JsonProcessingException
     */
    public String getGeocoding(String address) throws JsonProcessingException {
        RestTemplate restTemplate = new RestTemplate();
        String url = "https://restapi.amap.com/v3/geocode/geo";
        String key = "a17801c17c005c52b8c03d5e58f4202e";
        Map<String,String> params = new HashMap<>();
        params.put("key",key);
        params.put("address",address);
        String json = buildUrlWithParams(url,params);
        System.out.println("json===="+json);
        ResponseEntity<String> responseEntity = restTemplate.getForEntity(json, String.class);
        String responseBody = responseEntity.getBody();
        JsonNode jsonNode = JsonUtils.getObjectMapper().readTree(responseBody);
        JsonNode list = jsonNode.path("geocodes");
        JsonNode firstGeocode = list.get(0);
        // 获取 location
        String location = firstGeocode.path("location").asText();
        System.out.println("location"+location);
        return location;
    }
    private static String buildUrlWithParams(String url, Map<String, String> params) {
        StringBuilder urlBuilder = new StringBuilder(url);
        urlBuilder.append("?");
        for (Map.Entry<String, String> entry : params.entrySet()) {
            urlBuilder.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
        }
        // 去除末尾的 "&"
        urlBuilder.deleteCharAt(urlBuilder.length() - 1);
        return urlBuilder.toString();
    }
}